package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"novel-kit/model/cache"
	"novel-kit/model/mysql"
	"novel-kit/novelrpc/internal/svc"
	"novel-kit/novelrpc/novelrpc"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type CommentListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCommentListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CommentListLogic {
	return &CommentListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 评论列表
func (l *CommentListLogic) CommentList(in *novelrpc.CommentListRequest) (*novelrpc.CommentListResponse, error) {
	// todo: add your logic here and delete this line
	var findNovel mysql.Novel
	if err := findNovel.FindNovelById(mysql.DB, in.NovelId); err != nil {
		return nil, errors.New("小说不存在")
	}
	var commentList []*novelrpc.CommentList

	key := fmt.Sprintf("commentList%d", in.NovelId)
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result == "" {
		commentList = mysql.CommentList(mysql.DB, in.NovelId)
		marshal, _ := json.Marshal(commentList)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*15)
	} else {
		json.Unmarshal([]byte(result), &commentList)
	}

	return &novelrpc.CommentListResponse{
		List: commentList,
	}, nil
}
